package me.lijf.mqlite.config;

import me.lijf.mqlite.redis.message.MessageConsumer;
import me.lijf.mqlite.redis.message.MessageConsumer2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

@Configuration
public class RedisMessageConfig {
    @Autowired
    private RedisConnectionFactory connectionFactory;

    @Autowired
    private MessageConsumer listener;
    @Autowired
    private MessageConsumer2 listener2;

    @Value("${redis.message.topic}")
    private String topic;

    @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer(){
        RedisMessageListenerContainer container=new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.addMessageListener(this.adapt(listener),new PatternTopic(topic));
        container.addMessageListener(this.adapt(listener2),new PatternTopic(topic));
        return container;
    }

    private MessageListenerAdapter adapt(MessageListener listener){
        MessageListenerAdapter adapter=new MessageListenerAdapter(listener);
        adapter.setDefaultListenerMethod("onMessage");
        adapter.afterPropertiesSet();
        return adapter;
    }
}
